<?php
/**
 * 后台主界面
 * @Author 聂哥<376927050@qq.com>
 * @Date: 2022-10-11 19:50:59
*/

namespace app\admin\controller\system;

use app\admin\model\system\SystemMenu;
use app\admin\model\system\SystemRole as RoleModel;
use app\admin\model\system\SystemUserRole;
use app\admin\validate\system\Role as RoleValidate;
use Exception;
use think\Db;

class Role extends Base
{
    /**
     * 角色
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $list = RoleModel::order('id','desc')
                ->where('id','<>',1)
                ->field('auth,delete_time',true)
                ->paginate($this->request->get('limit'));
            return [
                'code' => 0,
                'msg' => '',
                'count' => $list->total(),
                'data' => $list->items(),
                'limit' => $this->request->get('limit')
            ];
        }
        return $this->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            //验证
            $validate = new RoleValidate;
            if(!$validate->check($data)){
                throw new Exception($validate->getError());
            }
            $role = new RoleModel();
            if($role->save($data) == false){
                throw new Exception('添加失败');
            }
            return ['code'=>200,'msg'=>'添加成功'];
        }
        return $this->fetch('form');
    }

    /**
     * 编辑
     */
    public function edit($id)
    {
        $role = RoleModel::find($id);
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            //验证
            $validate = new RoleValidate;
            if(!$validate->check($data)) {
                throw new Exception($validate->getError());
            }
            $role->name = $data['name'];
            $role->intro = $data['intro'];
            if( $role->save() == false ){
                throw new Exception('编辑角色失败');
            }
            return [
                'code' => 200,
                'msg'  => '编辑角色成功'
            ];
        }
        return $this->fetch('form',['formData' => $role]);
    }

    /**
     * 删除
     */
    public function del($id)
    {
        $role = RoleModel::find($id);
        if($role){
            Db::startTrans();
            try{
                //删除中间表
                SystemUserRole::where('role_id', $role['id'])->delete();
                $role->delete();
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                throw new Exception($e->getMessage());
            }
            return [
                'code' => 200,
                'msg'  => '删除角色成功'
            ];
        }
    }

    /**
     * 分配权限
     */
    public function menus($id)
    {
        $role = RoleModel::find($id);
        $menus = SystemMenu::order('sort','desc')->select();
        foreach ($menus as $menu){
            if ($role['auth'] != null){
                foreach (explode(',',$role['auth']) as $p){
                    if ($menu->id==$p){
                        $menu->own = true;
                    }
                }
            }
        }
        $menus = get_tree($menus->toArray());
        if ($this->request->isAjax()){
            $postMenus = $this->request->param('permissions');
            if(!isset($postMenus)){
                throw new Exception('至少选择一项');
            }
            $role->auth = implode(",",$postMenus);
            if( $role->save() == false ){
                throw new Exception('权限分配失败');
            }
            return [
                'code' => 200,
                'msg'  => '权限分配成功'
            ];
            
        }
        return $this->fetch('menus',[
            'menus' => $menus,
            'role' => $role,
        ]);
    }
}
